package com.zhu.tool_test.starke.framework.redis;


import com.zhu.tool_test.starke.framework.redis.annotations.EventHandler;
import com.zhu.tool_test.starke.framework.redis.annotations.QueueEvent;
import com.zhu.tool_test.starke.framework.redis.event.EventCollector;
import com.zhu.tool_test.starke.framework.redis.event.EventMethodInvoker;
import com.zhu.tool_test.starke.framework.redis.event.EventResponse;
import com.zhu.tool_test.starke.util.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @author  4everlynn
 * @version V1.0
 * @description 处理注解
 * @date 2019-04-16
 */
@Slf4j
public class EventProcesser implements ApplicationListener<ContextRefreshedEvent> {
    /**
     * 根据事件模块分发任务
     *
     * @param moduleName 事件模块名称
     */
    public void dispatch(String moduleName, EventResponse response) {
        List<EventMethodInvoker> eventHandler = EventCollector
                .instance().getEventHandler(moduleName, response.getEventName());
        for (EventMethodInvoker eventMethodInvoker : eventHandler) {
            eventMethodInvoker.invoke(response);
        }
    }

    /**
     * 初始化事件信息
     * 此时事件采集器开始采集EventHandler
     *
     * @param event Spring提供的事件回调
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(EventHandler.class);
            for (Object bean : beans.values()) {
                Method[] methods = bean.getClass().getMethods();
                for (Method method : methods) {
                    QueueEvent queueEvent = method.getDeclaredAnnotation(QueueEvent.class);
                    // 拥有QueueEvent注解的方法才会进行处理
                    if (null != queueEvent) {
                        String eventName = queueEvent.value();
                        if (!Strings.isNullOrEmpty(eventName)) {
                            // 采集事件以及执行对象
                            EventCollector.instance().collect(eventName, bean, method);
                        }
                    }
                }
            }
        }
    }
}
